'use client';

import {useEffect, useState} from 'react';
import styles from './WeatherPage.module.css';
import {getLocation} from "@/lib/utils";
import {getObj} from "@/services/api_service";

type ForecastData = {
    day: string;
    temperature: string;
    description: string;
};

type WeatherData = {
    location: string;
    forecast: ForecastData[];
};

export default function WeatherPage() {
    const [location, setLocation] = useState<{ latitude: number; longitude: number } | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [weather, setWeather] = useState<WeatherData | null>(null);
    useEffect(() => {
        getLocation({setLocation, setError});
    }, []);

    useEffect(() => {
        if (location) {
            const getForecast = async () => {
                const data: WeatherData = await getObj(`/api/weather/forecast/${location}`)
                setWeather(data)
            }

            getForecast()
                .catch((err) => console.error('Ошибка получения прогноза погоды:', err));
        }
    }, [location]);

    return (
        <div className={styles.weatherPage}>
            {weather ? (
                <>
                    <h1 className={styles.title}>Прогноз погоды для {weather.location}</h1>
                    <div className={styles.forecastList}>
                        {weather.forecast.map((dayForecast, index) => (
                            <div key={index} className={styles.forecastItem}>
                                <div className={styles.day}>{dayForecast.day}</div>
                                <div className={styles.temperature}>{dayForecast.temperature}°C</div>
                                <div className={styles.description}>{dayForecast.description}</div>
                            </div>
                        ))}
                    </div>
                </>
            ) : (
                <div className={styles.loading}>Загрузка прогноза погоды...</div>
            )}
        </div>
    );
}
